package com.wooming.myserver.controller;

import com.wooming.myserver.dto.JwtDTO;
import com.wooming.myserver.dto.UserDTO;
import com.wooming.myserver.entity.User;
import com.wooming.myserver.security.PasswordEncryption;
import com.wooming.myserver.service.inter.HeadshotService;
import com.wooming.myserver.service.inter.UserService;
import com.wooming.myserver.util.ApiObserver;
import com.wooming.myserver.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户相关API控制器
 *
 * @author wooming 2025/05/20
 */
@RestController
public class UserController {
    // 依赖项
    private final UserService userService;
    private final HeadshotService headshotService;

    // 依赖注入
    @Autowired
    public UserController(
            UserService userService,
            HeadshotService headshotService
    ) {
        this.userService = userService;
        this.headshotService = headshotService;
    }

    @PostMapping("/api/public/login")
    public Result<String> login(@RequestBody UserDTO userDTO) {
        System.out.println("有人访问登录接口");   //监控后端API调用
        User user = userService.findUser(userDTO.getUsername());
        if (user == null) {
            return Result.error(400, "用户不存在");
        } else {
            try {
                if (!PasswordEncryption.verify(userDTO.getPassword(), user.getPasswordHash())) {
                    return Result.error(400, "密码错误");
                }
            } catch (Exception e) {
                System.out.println(e.getMessage()); // 输出异常信息
                return Result.error(500, "服务器错误");
            }
        }
        try {
            String jwt = userService.getJWT(user);
            System.out.println("用户 " + user.getUsername() + " 登录成功");
            return Result.success(jwt);
        } catch (Exception e) {
            System.out.println(e.getMessage()); // 输出异常信息
            return Result.error(500, "服务器错误");
        }
    }

    @PostMapping("/api/public/register")
    public Result<String> register(@RequestBody UserDTO userDTO) {
        System.out.println("有人访问注册接口");   //监控后端API调用
        try {
            if (userService.register(userDTO.getUsername(), userDTO.getPassword())) { // 尝试注册
                System.out.println("用户 " + userDTO.getUsername() + " 注册并登录成功");
                // 返回JWT
                return Result.success(userService.getJWT(userService.findUser(userDTO.getUsername())));
            } else {
                return Result.error(400, "用户名已存在");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage()); // 输出异常信息
            return Result.error(500, "服务器错误");
        }
    }

    @PostMapping("/api/user/change")
    public Result<?> change(@RequestBody UserDTO userDTO) {
        // 监控API调用
        Result<?> result = ApiObserver.observe("用户信息更改");
        if (result.getCode() != 200) return result;

        // 获取认证信息
        JwtDTO jwtDTO = (JwtDTO) result.getData();

        // 构建新用户信息
        User user = new User();
        user.setId(jwtDTO.getSub());
        user.setUsername(userDTO.getUsername());
        user.setPasswordHash(userDTO.getPassword());

        try {
            return userService.changeInformation(user) ?
                    Result.success(userService.getJWT(user)) :
                    Result.error(400, "用户名已存在");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error(500, "服务器错误");
        }
    }

    @PostMapping("/api/public/verify")
    public Result<?> verify(@RequestBody String jwt) {
        System.out.println("有人访问jwt验证接口");   //监控后端API调用
        // 解JSON
        StringBuilder sb = new StringBuilder(jwt);
        sb.delete(0, 10);
        sb.delete(sb.length() - 2, sb.length());
        jwt = sb.toString();
        try {
            User user = headshotService.verify(jwt);
            return user == null ?
                    Result.error(401, "用户未登录") :
                    Result.success(user);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error(500, "服务器错误");
        }
    }
}
